package com.web;
import com.google.gson.Gson;
import com.pojo.Page;
import com.pojo.Tour;
import com.pojo.User;
import com.service.UserService;
import com.service.impl.UserServiceImpl;
import com.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();


    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求的参数username
        String username = req.getParameter("username");
        // 调用userService.existsUsername();
        boolean existsUsername = userService.existsUserName(username);
        // 把返回的结果封装成为map对象
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("existsUsername",existsUsername);

        Gson gson = new Gson();
        String json = gson.toJson(resultMap);

        resp.getWriter().write(json);
    }

    /**
     * 注销
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1、销毁Session中用户登录的信息（或者销毁Session）
        req.getSession().invalidate();
//        2、重定向到首页（或登录页面）。
        resp.sendRedirect(req.getContextPath());
    }
    /**
     * 处理登录的功能
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //  1、获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 调用 userService.login()登录处理业务
        User loginUser = userService.login(new User(username, password, null,null,null));
        // 如果等于null,说明登录 失败!
        if (loginUser == null) {
            // 把错误信息，和回显的表单项信息，保存到Request域中
            req.setAttribute("msg", "用户或密码错误！");
            req.setAttribute("username", username);
            //   跳回登录页面
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
        } else {
            // 登录 成功
            // 保存用户登录的信息到Session域中
            req.getSession().setAttribute("user", loginUser);
            //跳到成功页面login_success.html
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);
        }

    }

    /**
     * 处理注册的功能
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        // 获取Session中的验证码
//        String token = (String) req.getSession().getAttribute("KAPTCHA_SESSION_KEY");
//        // 删除 Session中的验证码
//        req.getSession().removeAttribute("KAPTCHA_SESSION_KEY");

        String token = "abcde";

        //  1、获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");

        User user = WebUtils.copyParamToBean(req.getParameterMap(), new User());

//        2、检查 验证码是否正确  === 写死,要求验证码为:abcde
        if (token!=null && token.equalsIgnoreCase(code)) {
//        3、检查 用户名是否可用
            if (userService.existsUserName(username)) {
                System.out.println("用户名[" + username + "]已存在!");

                // 把回显信息，保存到Request域中
                req.setAttribute("msg", "用户名已存在！！");
                req.setAttribute("username", username);
                req.setAttribute("email", email);

//        跳回注册页面
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
            } else {
                //      可用
//                调用Sservice保存到数据库
                userService.regist(user);
//
//        跳到注册成功页面 login_success.jsp
                req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);
            }
        } else {
            // 把回显信息，保存到Request域中
            req.setAttribute("msg", "验证码错误！！");
            req.setAttribute("username", username);
            req.setAttribute("email", email);

            System.out.println("验证码[" + code + "]错误");
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
        }

    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的参数id
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        //调用tourService.deleteTourById();删除用户
        userService.deleteUserById(id);
        //重定向回旅行团列表管理页面/tour/manage/tourServlet?action=list
        resp.sendRedirect(req.getContextPath() + "/userServlet?action=page&pageNo=" + req.getParameter("pageNo"));
    }

    protected void getUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 获取请求的参数旅行团编号
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        //2 调用tourService.queryTourById查询旅行团
        User user = userService.queryUserById(id);
        //3 保存到旅行团到Request域中
        req.setAttribute("user", user) ;
        //4 请求转发到。pages/manage/tour_add.jsp页面
        req.getRequestDispatcher("/pages/user/user_add.jsp").forward(req,resp);
    }

    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 获取请求的参数 pageNo 和 pageSize
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        //2 调用userService.page(pageNo，pageSize)：Page对象
        Page<User> page = userService.page(pageNo,pageSize);

        page.setUrl("userServlet?action=page");
        System.out.println(page);

        //3 保存Page对象到Request域中
        req.setAttribute("page",page);
        //4 请求转发到/pages/user/user_display.jsp页面
        req.getRequestDispatcher("/pages/user/user_display.jsp").forward(req,resp);
    }

    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int pageNo = Integer.parseInt(req.getParameter("pageNo"));
        pageNo++;


        //获取请求参数封装为bean对象

        User user = WebUtils.copyParamToBean(req.getParameterMap(),new User());

        //调用userService.regist()方法添加用户信息

        System.out.println(user);

        userService.regist(user);

        //通过/userService?action=list跳转回user_display.jsp页面

        resp.sendRedirect(req.getContextPath() + "/userServlet?action=page&pageNo=" + pageNo);

    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1、获取请求的参数==封装成为对象
        User user = WebUtils.copyParamToBean(req.getParameterMap(),new User());
        //2、调用userService.updateUser(user)修改用户
        userService.updateUser(user);
        //3、重定向回用户列表管理页面
        //地址：/工程名/manage/tourServlet?action=list
        resp.sendRedirect(req.getContextPath() + "/userServlet?action=page&pageNo=" + req.getParameter("pageNo"));
    }

}
